package com.zycoin.nio;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zhongyicheng
 * create date 2018/1/11.
 */
public class Dispatch implements  Runnable {
    private Selector selector;

    public Dispatch(Selector selector) {
        this.selector = selector;
    }

    public void run() {
        try {
            while (true) {
                selector.select();
//                if(selector.select(1000)>0) {
                    Set selected = selector.selectedKeys();
                    Iterator<SelectionKey> keyIt = selected.iterator();
                    while (keyIt.hasNext()) {
                        SelectionKey key = keyIt.next();
                        dispatch(key);
                        keyIt.remove();
                    }
                }
//            }
        } catch (IOException ex) { ex.printStackTrace(); }
    }

    void dispatch(SelectionKey k) {
        Runner r = (Runner) (k.attachment());
        if (r != null)
            r.run();
    }
}
